package me.zk.practice1.s;

/**
 * @author zhangkai
 * @date 2023/7/7 17:54
 */
public class LS22 {
    public ListNode getKthFromEnd(ListNode head, int k) {
        if (head == null) return null;
        ListNode slow = head, fast = head;
        for (int i = 0; i < k; i++) {

            if (fast == null) {
                return null;
            }
            fast = fast.next;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

    public ListNode getKthFromEnd2(ListNode head, int k) {
        int len = 0;
        ListNode cur = head;
        while (cur != null) {
            len++;
            cur = cur.next;
        }
        int index = len - k;
        cur = head;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        return cur;

    }
}
